<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

use App\Model\User;
use Hyperf\Context\Context;

if (! function_exists('di')) {
    /**
     * Finds an entry of the container by its identifier and returns it.
     * @return mixed|\Psr\Container\ContainerInterface
     */
    function di(?string $id = null)
    {
        $container = Hyperf\Context\ApplicationContext::getContainer();
        if ($id) {
            return $container->get($id);
        }

        return $container;
    }
}



if (! function_exists('get_app_user_have')) {
    function get_app_user_have()
    {
        return Context::get(\App\Model\User::APP_LOGIN_KEY);
    }
}

if (! function_exists('get_app_user')) {
    function get_app_user(): User
    {
        return Context::get(\App\Model\User::APP_LOGIN_KEY);
    }
}

if (! function_exists('set_app_user')) {
    function set_app_user(User $user)
    {
        return Context::set(User::APP_LOGIN_KEY, $user);
    }
}

function getOrderNum()
{
    // return date('YmdHis') . strtoupper(dechex((int) date('m'))) . date('d') . substr(strval(time()), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    return date('ymdHis') . substr(microtime(), 2, 4) . sprintf('%02d', rand(0, 99));
}

/*
 * 获取两位小数的合法数值
 *
 */
function formatNumbers($num, $length = 3)
{
    $temp = (string) $num;
    return substr(sprintf('%.'.$length.'f', $temp), 0, -1);
}

/*
查看字符串是否以某个字符结尾
$str 要检测的字符串
$suffix 要检测的字符
 */
function strEndWith($str, $suffix = '/')
{
    $length = strlen($suffix);
    if ($length == 0) {
        return false;
    }
    return substr($str, -$length) === $suffix;
}

/*
查看字符串是否以某个字符结尾
$str 要检测的字符串
$suffix 要检测的字符
 */
function strStartWith($str, $suffix = '')
{
    $length = strlen($suffix);
    if ($length == 0) {
        return false;
    }

    return mb_substr($str, 0, $length) === $suffix;
}

function isElevenDigitNumber($str) {
    // 使用正则表达式匹配是否是11位数字
    return (bool)preg_match('/^\d{11}$/', $str);
}
